package com.fzg.common.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fzg.common.tool.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * create by fzg
 * 2021/10/12 10:47
 */


public class MyInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 从前端请求中获取token
        String token = request.getHeader("token");
        Map<String,Object> map = new HashMap<>();
        if (token == null){
            map.put("state",false);
            map.put("msg","token为空");
        }else {
            try {
                JwtUtil.verify(token);
                Integer aid = Integer.parseInt(JwtUtil.getClaim(token,"aid"));
                request.setAttribute("aid",aid);
                return true;
            }catch (TokenExpiredException e){
                map.put("state",false);
                map.put("msg","token已过期！");
            }catch (SignatureVerificationException e){
                map.put("state",false);
                map.put("msg","签名错误！");
            }catch (AlgorithmMismatchException e){
                map.put("state",false);
                map.put("msg","加密算法不匹配");
            }catch (Exception e){
                map.put("state",false);
                map.put("msg","无效token！");
            }
        }

        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
